package listbyorder.access001_100.test60;

import java.util.ArrayList;
import java.util.List;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/2 11:36
 */
public class Solution3 {

    // 方法三： 迭代的写法
    public String getPermutation(int n, int k) {
        List<Integer> nums = new ArrayList<>();
        int factorial = 1;
        for (int i = 0; i < n; i++) {
            nums.add(i + 1);
            if (i != 0) {
                factorial *= i;
            }
        }
        factorial *= n;   // 首先计算出n的阶乘
        StringBuilder ans = new StringBuilder();
        k = k - 1;
        for (int i = n; i > 0; i--) {
            factorial /= (nums.size());
            int groupNum = k / factorial;
            int num = nums.get(groupNum);
            nums.remove(groupNum);
            k = k % factorial;
            ans.append(num);
        }
        return ans.toString();
    }
}
